//
//  ContactViewModel.m
//  BrushFace
//
//  Created by 小小旭 on 15/12/23.
//  Copyright © 2015年 Zzz. All rights reserved.
//

#import "ContactViewModel.h"
#import "ContactModel.h"
#import "pinyin.h"
#import "AppStatus.h"

@implementation ContactViewModel

- (void)loadSceneModel {
    [super loadSceneModel];
    _dataSource = [NSMutableArray array];
}

-(NSString*)upperStr:(NSString*)str{
    NSString *lowerStr = [str lowercaseStringWithLocale:[NSLocale currentLocale]];
    return lowerStr;
}

//获取一度好友列表
- (void)connection_getLevel1RelationAndCB:(void (^)(id output))CB{
    NSString *requestStr = [NSString stringWithFormat:@"%@/connection/getlevel1relation.json",SERVICE_ADRESS];
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    manager.responseSerializer = [[AFHTTPResponseSerializer alloc] init];
    [manager GET:requestStr parameters:nil success:^(AFHTTPRequestOperation * _Nonnull operation, id  _Nonnull responseObject) {
        NSDictionary *jsonObject = [NSJSONSerialization JSONObjectWithData:responseObject options:0 error:nil];
        NSMutableDictionary*index=[NSMutableDictionary dictionaryWithCapacity:0];
        for (NSDictionary *dic in jsonObject[@"contact"]) {
            NSString* str=dic[@"nickName"];
            str = [self replayBaseStr:str];
            NSString *strFirLetter;
            if ([self isLetter:str])
            {
                strFirLetter= [self upperStr:[str substringToIndex:1]];
            }
            else
            {
                strFirLetter = [NSString stringWithFormat:@"%c",pinyinFirstLetter([str characterAtIndex:0])];
            }
            if ([[index allKeys]containsObject:strFirLetter]) {
                //判断index字典中，是否有这个key如果有，取出值进行追加操作
                [[index objectForKey:strFirLetter] addObject:dic];
            }else{
                NSMutableArray*tempArray=[NSMutableArray arrayWithCapacity:0];
                [tempArray addObject:dic];
                [index setObject:tempArray forKey:strFirLetter];
            }
        }
        CB(index);
    } failure:^(AFHTTPRequestOperation * _Nullable operation, NSError * _Nonnull error) {
        
    }];
}

- (void)connection_getLevel2RelationAndCB:(void(^)(id output))CB{
    NSString *requestStr = [NSString stringWithFormat:@"%@/connection/getlevel2relation.json",SERVICE_ADRESS];
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    manager.responseSerializer = [[AFHTTPResponseSerializer alloc] init];
    [manager GET:requestStr parameters:nil success:^(AFHTTPRequestOperation * _Nonnull operation, id  _Nonnull responseObject) {
        NSDictionary *jsonObject = [NSJSONSerialization JSONObjectWithData:responseObject options:0 error:nil];
        NSMutableDictionary*index=[NSMutableDictionary dictionaryWithCapacity:0];
        for (NSDictionary *dic in jsonObject[@"contact"]) {
            NSString* str = dic[@"nickName"];
            str = [self replayBaseStr:str];
            
            NSString *strFirLetter;
            if ([self isLetter:str])
            {
               strFirLetter= [self upperStr:[str substringToIndex:1]];
            }
            else
            {
                strFirLetter = [NSString stringWithFormat:@"%c",pinyinFirstLetter([str characterAtIndex:0])];
             }
            
                      if ([[index allKeys]containsObject:strFirLetter])
            {
                //判断index字典中，是否有这个key如果有，取出值进行追加操作
                [[index objectForKey:strFirLetter] addObject:dic];
            }
            else
            {
                NSMutableArray*tempArray=[NSMutableArray arrayWithCapacity:0];
                [tempArray addObject:dic];
                [index setObject:tempArray forKey:strFirLetter];
            }
        }
        CB(index);
    } failure:^(AFHTTPRequestOperation * _Nullable operation, NSError * _Nonnull error) {
        
    }];
}

- (NSString *)replayBaseStr:(NSString *)nickName
{
    NSMutableString *nickN = [[NSMutableString alloc]initWithString:nickName];
    NSMutableString *retStr = [[NSMutableString alloc] init];
    for (int i=0; i<nickN.length; i+=4) {
        NSString *subStr = [NSString stringWithFormat:@"\\u%@",[nickN substringWithRange:NSMakeRange(i, 4)]];
        [retStr appendString:[self replaceUnicode:subStr]];
    }
    return retStr;
}

- (NSString *)replaceUnicode:(NSString *)unicodeStr {
    NSString *tempStr1 = [unicodeStr stringByReplacingOccurrencesOfString:@"\\u" withString:@"\\U"];
    NSString *tempStr2 = [tempStr1 stringByReplacingOccurrencesOfString:@"\"" withString:@"\\\""];
    NSString *tempStr3 = [[@"\"" stringByAppendingString:tempStr2] stringByAppendingString:@"\""];
    NSData *tempData = [tempStr3 dataUsingEncoding:NSUTF8StringEncoding];
    NSString* returnStr = [NSPropertyListSerialization propertyListFromData:tempData
                                                           mutabilityOption:NSPropertyListImmutable
                                                                     format:NULL
                                                           errorDescription:NULL];
    
    return [returnStr stringByReplacingOccurrencesOfString:@"\\r\\n" withString:@"\n"];
}

/**
 *  上传通讯录
 */
- (void)connection_uploadAddressBookWithArray:(NSMutableArray *)array andCB:(void(^)(id output))CB{
    if ([AppStatus whetherUploadAddressBook]) {
        NSString *requestStr = [NSString stringWithFormat:@"%@/addressbook/uploadaddressbook.json",SERVICE_ADRESS];
        NSData *jsonData = [NSJSONSerialization dataWithJSONObject:array options:NSJSONWritingPrettyPrinted error:nil];
        NSMutableString *str = [[NSMutableString alloc]initWithString:[[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding]];
        NSDictionary *params = @{@"addressbooks": str};
        AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
        manager.responseSerializer = [[AFHTTPResponseSerializer alloc] init];
        [manager POST:requestStr parameters:params success:^(AFHTTPRequestOperation * _Nonnull operation, id  _Nonnull responseObject) {
            NSDictionary *jsonDict = [NSJSONSerialization JSONObjectWithData:responseObject options:0 error:nil];
            if ([[jsonDict objectForKey:@"result"] integerValue]==1) {
               [AppStatus saveUploadAddressbook];
                CB(@"通讯录上传成功");
            }else{
                CB(@"通讯录上传失败");
            }
        } failure:^(AFHTTPRequestOperation * _Nullable operation, NSError * _Nonnull error) {
            
        }];
    }else{
        CB(@"通讯录不需要上传");
    }
}
//获取新的好友列表
- (void)addressBook_GetNewFriendListAndCB:(void(^)(id output))CB{
    NSString *requestStr = [NSString stringWithFormat:@"%@/addressbook/getnewfriendlist.json",SERVICE_ADRESS];
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    manager.responseSerializer = [[AFHTTPResponseSerializer alloc] init];
    [manager GET:requestStr parameters:nil success:^(AFHTTPRequestOperation * _Nonnull operation, id  _Nonnull responseObject) {
        NSDictionary *jsondict = [NSJSONSerialization JSONObjectWithData:responseObject options:0 error:nil];
        CB(jsondict);
    } failure:^(AFHTTPRequestOperation * _Nullable operation, NSError * _Nonnull error) {
        
    }];
}

/**
 *  获取好友详细信息
 */
- (void)fetchFriendDetailInfoWithUserId:(NSString *)userid andCB:(void(^)(id output))CB{
    NSString *requestStr = [NSString stringWithFormat:@"%@/addressbook/getuserinfobyfrienduseridinaddressbook.json",SERVICE_ADRESS];
    NSDictionary *params = @{@"frienduserid":userid};
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    [manager GET:requestStr parameters:params success:^(AFHTTPRequestOperation * _Nonnull operation, id  _Nonnull responseObject) {
        CB(responseObject);
    } failure:^(AFHTTPRequestOperation * _Nullable operation, NSError * _Nonnull error) {
        
    }];
}
/**
 *  查询请求添加的详细信息
 */
- (void)fetchFriendDetailWithRequestWithUserId:(NSString *)userid andCB:(void(^)(id output))CB{

    NSString *requestStr = [NSString stringWithFormat:@"%@/addressbook/getfriendmessageinfo.json",SERVICE_ADRESS];
    NSDictionary *params = @{@"friendmessageid":userid};
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    [manager GET:requestStr parameters:params success:^(AFHTTPRequestOperation * _Nonnull operation, id  _Nonnull responseObject) {
        CB(responseObject);
    } failure:^(AFHTTPRequestOperation * _Nullable operation, NSError * _Nonnull error) {
        
    }];
}
/**
 *  搜索好友
 */
- (void)searchUserWithPhone:(NSString *)phone andCB:(void(^)(id output))CB{
    NSString *requestStr = [NSString stringWithFormat:@"%@/addressbook/getuserinfobyphoneinaddressbook.json",SERVICE_ADRESS];
    NSDictionary *params = @{@"phone":phone};
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    [manager GET:requestStr parameters:params success:^(AFHTTPRequestOperation * _Nonnull operation, id  _Nonnull responseObject) {
        CB(responseObject);
    } failure:^(AFHTTPRequestOperation * _Nullable operation, NSError * _Nonnull error) {
        
    }];

}

/**
 *  添加好友
 */
- (void)addFriendWithFriendID:(NSString *)friendID andMessage:(NSString *)message andSource:(NSString *)source andCB:(void(^)(id output))CB{
    NSString *requestStr = [NSString stringWithFormat:@"%@/addressbook/askformakefriend.json",SERVICE_ADRESS];
    NSDictionary *params = @{@"frienduserid":friendID,
                             @"message":[self replayRequestStr:message],
                                 @"source":source};
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    [manager GET:requestStr parameters:params success:^(AFHTTPRequestOperation * _Nonnull operation, id  _Nonnull responseObject) {
        CB(responseObject);
    } failure:^(AFHTTPRequestOperation * _Nullable operation, NSError * _Nonnull error) {
        
    }];
}

/**
 *  获取手机联系人
 */
- (void)fetchAllFriendInAddressBookAndCB:(void(^)(id output))CB{

    NSString *requestStr = [NSString stringWithFormat:@"%@/addressbook/getallfriendlist.json",SERVICE_ADRESS];
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    [manager GET:requestStr parameters:nil success:^(AFHTTPRequestOperation * _Nonnull operation, id  _Nonnull responseObject) {
        NSDictionary *jsonObject = [NSJSONSerialization JSONObjectWithData:operation.responseData options:0 error:nil];
        NSMutableDictionary*index=[NSMutableDictionary dictionaryWithCapacity:0];
        for (NSDictionary *dic in jsonObject[@"friends"]) {
            NSString* str=[NSString stringWithFormat:@"%@",dic[@"friendname"]];
            //str = [self replayBaseStr:str];
            //获得中文拼音首字母，如果是英文或数字则#
            NSString *strFirLetter = [NSString stringWithFormat:@"%c",pinyinFirstLetter([str characterAtIndex:0])];
            if ([strFirLetter isEqualToString:@"#"]) {
                //转换为小写
                strFirLetter= [self upperStr:[str substringToIndex:1]];
            }
            if ([[index allKeys]containsObject:strFirLetter]) {
                //判断index字典中，是否有这个key如果有，取出值进行追加操作
                [[index objectForKey:strFirLetter] addObject:dic];
            }else{
                NSMutableArray*tempArray=[NSMutableArray arrayWithCapacity:0];
                [tempArray addObject:dic];
                [index setObject:tempArray forKey:strFirLetter];
            }
        }
        CB(index);
    } failure:^(AFHTTPRequestOperation * _Nullable operation, NSError * _Nonnull error) {
        
    }];
    
}

-(BOOL)isLetter:(NSString *)str
{
    NSString *firstStr = [str substringToIndex:1];
     NSString *ZIMU = @"^[A-Za-z]";
    NSPredicate *regextestA = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", ZIMU];
    if ([regextestA evaluateWithObject:firstStr] == YES)
    {
        return YES;
    }
    else
    {
        return NO;
    }
}
@end
